package com.atguigu.day07;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.*;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Comparator;

public class Flink03_KeyedState_ReducingState {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);


        //3.使用map将度过来的数据转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> result = streamSource.map(
                new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });

        //4.将相同ID的数据聚合到一块
        KeyedStream<WaterSensor, Tuple> keyedStream = result.keyBy("id");

        //TODO 5.求每个传感器水位和
        keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {
            //TODO a.定义状态
            private ReducingState<Integer> reducingState;

//            private ValueState<Integer> lastSum;


            //TODO b.初始化状态
            @Override
            public void open(Configuration parameters) throws Exception {
                reducingState = getRuntimeContext().getReducingState(new ReducingStateDescriptor<Integer>("reduce-state", new ReduceFunction<Integer>() {
                    @Override
                    public Integer reduce(Integer value1, Integer value2) throws Exception {
                        return value1 + value2;
                    }
                }, Integer.class));


//                lastSum = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("value-State", Integer.class,0));
            }

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                //1.将数据存入状态自动做累加操作
                reducingState.add(value.getVc());

                //2.取出状态中的值（累加后的结果）
                Integer vcSum = reducingState.get();

                out.collect(value.getId()+"-"+vcSum);


              /*  //1.取出状态中的上一次计算结果
                Integer lastSumResult = lastSum.value();

                //2.与当前的vc做累加
                int curVcSum = lastSumResult + value.getVc();

                //3.将当前的计算结果更新到状态中
                lastSum.update(curVcSum);


                out.collect(value.getId()+"-"+curVcSum);*/

            }
        }).print();

        env.execute();
    }

}
